package dao;

import hibernate.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class DAO {
	protected static SessionFactory sf = null;
	protected Session s;
	
	public DAO() {
		sf = HibernateUtil.getSessionFactory();
	}

	public void guardar(Object obj) {
		s = this.getSession();
		s.beginTransaction();
		s.persist(obj);
		s.getTransaction().commit();
		s.flush();
		s.close();
	}

	public Object buscar(String className, String campo, Integer id) {
		Session s = this.getSession();
		Object r = s.createQuery(
				"from " + className + " s where s." + campo + " = ?")
				.setInteger(0, id).list().get(0);
		s.close();
		return r;
	}

	public Object buscar(String className, String campo, String id) {
		try {
			Session s = this.getSession();
			return s.createQuery(
					"from " + className + " s where s." + campo + " = ?")
					.setString(0, id).list().get(0);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			s.close();
		}
		return null;
	}

	public void saveOrUpdate(Object obj) {
		Session s = this.getSession();
		s.saveOrUpdate(obj);
		s.close();
	}

	public Session getSession() {
		if(this.s == null || this.s.isOpen()==false)
			s = sf.openSession();
		return s;
	}

}
